

//==================================================================================
//  Declear variables 
//==================================================================================
var oFacebook = null;
var sessionKey = null;
var feedTimer = null;

//==================================================================================
//  GadgetInit 
//==================================================================================
function GadgetInit() 
{
    System.Gadget.settingsUI = "gadgetsettings.htm";
    System.Gadget.onSettingsClosed = SettingsClosed;
}

//==================================================================================
//  SettingsLoading
//==================================================================================
function SettingsLoading()
{
    System.Gadget.onSettingsClosing = SettingsClosing;
    document.getElementById("txtToken").value = System.Gadget.Settings.read("Token");
    document.getElementById("txtSqlServer").value = System.Gadget.Settings.read("SqlServerName");
    if (System.Gadget.Settings.read("timeIntervalIndex") + "" == "") System.Gadget.Settings.write("timeIntervalIndex", -1);
    document.getElementById("timeInterval").value = System.Gadget.Settings.read("timeIntervalIndex");
}

//==================================================================================
//  SettingsClosing
//==================================================================================
function SettingsClosing(args)
{
    if (args.closeAction == args.Action.commit)
    {
        System.Gadget.Settings.write("Token", document.getElementById("txtToken").value);
        System.Gadget.Settings.write("SqlServerName", document.getElementById("txtSqlServer").value);
        System.Gadget.Settings.write("timeIntervalIndex", document.getElementById("timeInterval").value);
    }
}

//==================================================================================
//  SettingsClosed
//==================================================================================
function SettingsClosed(event)
{
    if (event.closeAction == event.Action.commit) 
    {
        // If there is no token.
        if (System.Gadget.Settings.read("Token") + "" == "") 
        {
            showErrorPage("Please input a Facebook code!");
            return;
        }
        
        // If there is no sqlservername.
        if (System.Gadget.Settings.read("SqlServerName") + "" == "") 
        {
            showErrorPage("Please input a SQL Server name!"); 
            return;
        }
        
        try
        {
            oFacebook = new FaceBookClass();
            if (sessionKey == null || sessionKey == "") sessionKey = oFacebook.getSessionKey();
            if (sessionKey != "")
            {
                clearInterval(feedTimer);
                feedTimer = null;
            
                RefreshDisplay();
                showNotificationsPage();
                feedTimer = setInterval(RefreshDisplay, getTimeInterval());     
            }
            else
                showErrorPage("Invalid session key!");   
        }
        catch (e) 
        { 
            showErrorPage(e.message);
        }
    }
}

//==================================================================================
//  showWelcomePage
//==================================================================================
function showWelcomePage()
{
    document.getElementById("initpage").style.display = "block";
    document.getElementById("resultspage").style.display = "none";
    document.getElementById("errorpage").style.display = "none";
}

//==================================================================================
//  showNotificationsPage
//==================================================================================
function showNotificationsPage()
{
    document.getElementById("initpage").style.display = "none";
    document.getElementById("resultspage").style.display = "block";
    document.getElementById("errorpage").style.display = "none";
}

//==================================================================================
//  showErrorPage
//==================================================================================
function showErrorPage(error)
{
    document.getElementById("initpage").style.display = "none";
    document.getElementById("resultspage").style.display = "none";
    document.getElementById("errorpage").style.display = "block";
    document.getElementById("noteError").innerText = error;   
}

//==================================================================================
//  Get time interval for refresh.
//==================================================================================
function getTimeInterval()
{
    var index = System.Gadget.Settings.read("timeIntervalIndex"); 
    if (index == -1) return 15000;      // 15 seconds
    if (index == 0) return 30000;       // 30 seconds
    if (index == 1) return 60000;       // 1 minute
    if (index == 2) return 300000;      // 5 minutes
    return 3600000;                     // 1 hour
}

//==================================================================================
//  Refreshes with info the gadget's main window
//==================================================================================
function RefreshDisplay()
{
    // Get the current user.
    var me = oFacebook.getCurrentUser(sessionKey);
    // Get notifications
    var nots = oFacebook.getNotifications(sessionKey);
    
    var userID = me.id;
    var msgCount = nots.Messages.Count;
    var msgMostRecent = nots.Messages.LastID;
    var pokeCount = nots.Pokes.Count;
    var pokeMostRecent = nots.Pokes.LastID;
    var shareCount = nots.Shares.Count;
    var shareMostRecent = nots.Shares.LastID;
    var friendinvitationCount = nots.FriendInvitations.Count;
    var groupinvitationCount = nots.GroupInvitations.Count;
    var eventinvitationCount = nots.EventInvitations.Count;
    var msgReceived = false;
    var pokeReceived = false;
    var shareReceived = false;
    var friendreqReceived = false;
    var groupinvtReceived = false;
    var eventinvtReceived = false;
    
    var conn = new ActiveXObject("ADODB.Connection");
    var connstr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=FBDatabase;Data Source=" + System.Gadget.Settings.read("SqlServerName");
    var sql = "SELECT * FROM FaceBookAlerts where FacebookID=" + userID;
    var rst = new ActiveXObject("ADODB.recordset");
    
    // Open the connection.
    conn.Open(connstr);   
    
    // Get the recordset.      
    rst = conn.Execute(sql);
    
    // Insert or update the record.
    if (!rst.EOF)
    {
	    if (msgMostRecent != rst(3) && msgCount > rst(2)) msgReceived = true;
	    if (pokeMostRecent != rst(5) && pokeCount > rst(4)) pokeReceived = true;
	    if (shareMostRecent != rst(7) && shareCount > rst(6)) shareReceived = true;
	    if (friendinvitationCount > rst(8)) friendreqReceived = true;
	    if (groupinvitationCount > rst(9)) groupinvtReceived = true;
	    if (eventinvitationCount > rst(10)) eventinvtReceived = true;
	    
	    sql = "Update FaceBookAlerts SET";
	    sql += " unreadmsg=" + msgCount;
	    if (msgReceived) sql += ",mostrecentmsg=" + msgMostRecent + ",mostrecentmsgtime=GETDATE()";
        sql += ",unreadpoke=" + pokeCount;
        if (pokeReceived) sql += ",mostrecentpoke=" + pokeMostRecent + ",mostrecentpoketime=GETDATE()";
        sql += ",unreadshare=" + shareCount;
        if (shareReceived) sql += ",mostrecentshare=" + shareMostRecent + ",mostrecentsharetime=GETDATE()";
        sql += ",friendrequests=" + friendinvitationCount;
        if (friendreqReceived) sql += ",friendrequeststime=GETDATE()";
        sql += ",groupinvites=" + groupinvitationCount;
        if (groupinvtReceived) sql += ",groupinvitestime=GETDATE()"; 
        sql += ",eventinvites=" + eventinvitationCount;
        if (eventinvtReceived) sql += ",eventinvitestime=GETDATE()"
        sql += " where FacebookID=" + userID;
        conn.Execute(sql);
    }   
    else
    {
        sql = "insert into FaceBookAlerts(FaceBookID,Name,unreadmsg,mostrecentmsg,unreadpoke,mostrecentpoke,unreadshare,mostrecentshare,friendrequests,groupinvites,eventinvites) " +
              "values(" + userID + ",'" + me.name + "'," + msgCount + "," + msgMostRecent + "," + pokeCount + "," + pokeMostRecent + "," + shareCount + "," + shareMostRecent + "," + friendinvitationCount + ","  + groupinvitationCount + ","  + eventinvitationCount + ")";
        conn.Execute(sql);
    }
    
    // Display the current user's name.
    document.getElementById("facebookusername").innerText = me.name;   
        
    // Display of the records counts.
    document.getElementById("messageCount").innerText = msgCount; 
    document.getElementById("pokeCount").innerText = pokeCount; 
    document.getElementById("shareCount").innerText = shareCount; 
    document.getElementById("friendInvitesCount").innerText = friendinvitationCount;
    document.getElementById("groupInvitesCount").innerText = groupinvitationCount;  
    document.getElementById("eventInvitesCount").innerText = eventinvitationCount; 
    
    // Display of the received time.
    var Now = new Date();
    var Then;  
    if (!rst.EOF)
    {
        // Messages
        if (!msgReceived) 
        {
            if (String(rst(11)) == "null" || msgCount == 0)
                document.getElementById("messageTime").innerText = "";
            else
            {
                Then = new Date(rst(11));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("messageTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else
                    document.getElementById("messageTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("messageTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
	    
        // Pokes
        if (!pokeReceived) 
        {
            if (String(rst(12)) == "null" || pokeCount == 0)
                document.getElementById("pokeTime").innerText = "";
            else
            {
                Then = new Date(rst(12));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("pokeTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else 
                    document.getElementById("pokeTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("pokeTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
	    
        // Shares
        if (!shareReceived) 
        {
            if (String(rst(13)) == "null" || shareCount == 0)
                document.getElementById("shareTime").innerText = "";
            else
            {
                Then = new Date(rst(13));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("shareTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else 
                    document.getElementById("shareTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("shareTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
	    
        // Friends Requests
        if (!friendreqReceived) 
        {
            if (String(rst(14)) == "null" || friendinvitationCount == 0)
                document.getElementById("friendInvitesTime").innerText = "";
            else
            {
                Then = new Date(rst(14));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("friendInvitesTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else 
                    document.getElementById("friendInvitesTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("friendInvitesTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
	    
        // Group Invitations
        if (!groupinvtReceived) 
        {
            if (String(rst(15)) == "null" || groupinvitationCount == 0)
                document.getElementById("groupInvitesTime").innerText = "";
            else
            {
                Then = new Date(rst(15));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("groupInvitesTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else 
                    document.getElementById("groupInvitesTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("groupInvitesTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
	    
        // Event Invitations
        if (!eventinvtReceived) 
        {
            if (String(rst(16)) == "null" || eventinvitationCount == 0)
                document.getElementById("eventInvitesTime").innerText = "";
            else
            {
                Then = new Date(rst(16));
                if (Then.toDateString() == Now.toDateString()) 
                    document.getElementById("eventInvitesTime").innerText = "(" + Then.toTimeString().substring(0,8) + ")";
                else 
                    document.getElementById("eventInvitesTime").innerText = "(" + (Then.getMonth()+1) + "/" + Then.getDate() + "/" + Then.getFullYear().toString().substring(2,4) + ")";
            }
        }
        else 
            document.getElementById("eventInvitesTime").innerText = "(" + Now.toTimeString().substring(0,8) + ")";
    }
    
    // Close the recordset.
    rst.Close;
   
    // Close the connection.
    conn.Close();     
}